<?php

namespace App\Http\Controllers;
use App\Admin\Eloquent\Code;
use App\Admin\Eloquent\ProjectProfit;
use App\Eloquent\Projects;
use App\Eloquent\ProjectAttr;
use App\Eloquent\ProfitRole;
use App\Admin\Eloquent\ProjectsUser;
use App\Eloquent\ProjectTypeTemplates;
use App\Admin\Eloquent\GiftReceive;
use App\Admin\Eloquent\GiftActivity;
use App\Extensions\Pagination\BoosstrapPageProject;
use DB;
use App\Eloquent\FriendlyLink;
use App\Eloquent\User;
use App\Eloquent\Ad;
use App\Eloquent\Article;
use App\Eloquent\ArticleCategory;
use CreateHostingDeposit;
use \Illuminate\Http\Request;
use QueryBalance;
use Log;

class HomeController extends Controller
{
    /**
     * 主页
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //获取首页所有广告位
        $home_ads=Ad::getShareAds('ads_home');
        $homes_ads=array();
        foreach($home_ads as $home_ad){
            //把获取的广告位分类
            //海报
            if($home_ad->position=='ads_home_photo'){
                $banners[]=$home_ad;
                $homes_ads['ads_home_photo']=$banners;
            }
            //一号广告位
            if($home_ad->position=='ads_home_one'){
                $homes_ads['ads_home_one']=$home_ad;
            }
            //二号广告位
            if($home_ad->position=='ads_home_two'){
                $homes_ads['ads_home_two']=$home_ad;
            }
            //三号广告位
            if($home_ad->position=='ads_home_three'){
                $three_ads[]=$home_ad;
                $homes_ads['ads_home_three']=$three_ads;
            }
            //四号广告位
            if($home_ad->position=='ads_home_four'){
                $homes_ads['ads_home_four']=$home_ad;
            }

        }

        /*
         * 获取公告
         */
        $news_cates=ArticleCategory::get_child_categories('1');
        foreach($news_cates as $news_cate){
            $cates[]=$news_cate->id;
        }
        $news=Article::whereIn('article_category_id',$cates)
                ->where('recommended',1) //推荐
                ->where('display',1)      //显示
                ->where('published_at','<=',date('Y-m-d H:i:s'))  //到发布时期
                ->orderBy('published_at','desc')  //发布日期降序
                ->orderBy('sort','desc')          //sort降序
                ->get();
        $news=collect($news)->groupBy('article_category_id');
        $new_news=array();
        foreach($news as $key=>$new){
            $new=$new->take(1);
            $new_news[]=$new['0'];
        }
//        foreach($news_cates as $news_cate){
//            $cate_articles=Article::where('article_category_id',$news_cate->id)
//                ->where('recommended',1) //推荐
//                ->where('display',1)      //显示
//                ->where('published_at','<=',date('Y-m-d H:i:s'))  //到发布时期
//                ->orderBy('published_at','desc')  //发布日期降序
//                ->orderBy('sort','desc')          //sort降序
//                ->first();
//            $news[]=$cate_articles;
//        }
        /*
         * 获取平台数据
         */
        //累计撮合融资金额
        $status=array('payment','finish');
        $finance=Projects::whereIn('status',$status)->sum('financed_money');
        $earn=ProjectProfit::where('role_slug','User')->sum('profit');
        //风险备付金
//        $params['identity_id']=config('sinapay.partner_id');
//        $params['identity_type']='MEMBER_ID';
//        $params['account_type']='ENSURE';
//        $bei_fu_jin_reasult=QueryBalance::send($params);
//        dd($bei_fu_jin_reasult);
        $record=[
            //累计撮合融资金额
            'finance'=>number_format($finance,2),
            //累计为投资人赚取收益
            'earn'=>number_format($earn,2),
            //风险备付金
        ];

        /*
         * 获取推荐栏项目
         */
        $project_recommend=Code::where('type_id','=','recommend_project')->get();
        $recomnmend_project_ids=array();
        foreach($project_recommend as $recomnmend){
            $recomnmend_project_ids[]=$recomnmend->description;
        }
        $recomnmend_projects=array();
        $recomnmend_project=Projects::join('codes','codes.code','=','repayment')
            ->whereIn('id',$recomnmend_project_ids)
            ->orderBy('created_at','desc')
            ->select('codes.name as repayment_name','projects.*')
            ->get();
        $i=0;
        foreach($recomnmend_project as $a){
            $recomnmend_projects[$i]=$a;
            $i++;
        }
        $recomnmend_project_num=$recomnmend_project->count();
        $beginners=Projects::join('codes','codes.code','=','repayment')
            ->where('new_projects',1)
            ->orderBy('created_at','desc')
            ->limit(2-$recomnmend_project_num)
            ->select('codes.name as repayment_name','projects.*')
            ->get();
        foreach($beginners as $b){
            $recomnmend_projects[$i]=$b;
            $i++;
        }
        if(collect($recomnmend_projects)->count()){
            $recomnmend_projects=Projects::getalltail($recomnmend_projects);
        }

        /*
         * 获取精选项目
         */
        $project_codes=ProjectTypeTemplates::limit(4)->get();
        foreach($project_codes as $key=> $project_code){
//            $r_project_codes[$key]=$project_code->id;
//            $r_projects[$project_code->id]=array();
            $status=array('rush','full','payment','finish','late','fail');
            $projects[$project_code->id]=Projects::join('codes','codes.code','=','repayment')
                ->join('codes as code','code.code','=','status')
                ->where('project_type_template_id',$project_code->id)
                ->where('start_time','<=',date('Y-m-d H:i:s'))
                ->where('new_projects',0)
                ->whereIn('status',$status)
                ->orderBy('code.sort','desc')
                ->orderBy('created_at','desc')
                ->limit(3)
                ->select('codes.name as repayment_name','projects.*')
                ->get();
        }
        foreach($projects as $key=> $to_project){
            $to_project->count()==0 or $to_project=Projects::getalltail($to_project);
            $r_projects[$key]=$to_project;
        }
//        $projects=Projects::getProjects('projects',$r_project_codes);
//        $projects=collect($projects)->groupBy('projects_code');
//
//        foreach($projects as $key=>$project){
//            $to_project=$project->take(3);
//            $to_project->count()==0 or $to_project=Projects::getalltail($to_project);
//            $r_projects[$key]=$to_project;
//        }
        /*
         * 获取文章分类
         */
        $cates=ArticleCategory::get_child_categories('4');
        /*
         * 获取分类下的文章
         */
        foreach($cates as $cate){
            $articles_cates[]=$cate->id;
        }
        $cates_articles=Article::whereIn('article_category_id',$articles_cates)
            ->where('recommended',1) //推荐
            ->where('display',1)      //显示
            ->where('published_at','<=',date('Y-m-d H:i:s'))  //到发布时期
            ->orderBy('published_at','desc')  //发布日期降序
            ->orderBy('sort','desc')          //sort降序
            ->get();
        $articles=array();
        $cates_articles=collect($cates_articles)->groupBy('article_category_id');
        foreach($cates_articles as $key=>$cates_article){
            $cates_article=$cates_article->take(5);
            $articles[$key]=$cates_article;
        }
        //获取合作机构
        $friendly_links=FriendlyLink::getFriendlyLink('friend_link_one','10');

        $data=[
//            //海报图
//            'banners'=>$banner,
            //公告
            'news'=>$new_news,
            //广告位广告
            'homes_ads'=>$homes_ads,
//            'one_ads'=>$one_ads,
//            'two_ads'=>$two_ads,
//            'three_ads'=>$three_ads,
//            'four_ads'=>$four_ads,
            //新手标
            'beginners'=>$recomnmend_projects,
            //精选项目
            'project_codes'=>$project_codes,
            'projects'=>$r_projects,
            //平台数据
            'record'=>$record,
            //文章分类
            'cates'=>$cates,
            //文章分类的文章
            'cates_articles'=>$articles,
            //获取合作机构
            'friendly_links'=>$friendly_links,

        ];
        return view('web.home.index',$data);
    }

    //登录
    public function login(){
        session()->put('user_id','1');
        session()->put('user_name','已登录');

        return redirect('/');
    }
    //注册
    public function register(){
        return '注册';
    }
    //个人中心
    public function user(){
        return '个人中心';
    }
    //账户中心
    public function money(){
        return '账户中心';
    }
    //退出登录
    public function logout(){
        session()->flush();
        return redirect('/');
    }
    //充值
    public function pay(){
        return '充值';
    }
    //提现
    public function withdraw(){
        return '提现';
    }
    //我的投资
    public function myInvest(){
        return '我的投资';
    }
    //我的借款
    public function myBorrow(){
        return '我的借款';
    }
    /*
     * 更多公告
     */
    public function moreNotice(){
        return redirect('/articles/notice');
    }
    /*
     * 更多新手标
     */
    public function moreBeginner(){
        return '更多新手标';
    }
    public function oneBeginner($id){
        return $id.'单个新手标';
    }

    /*
     * 更多数据
     */
    public function moreRecord(){
        return '更多平台数据';
    }
    /*
     * 更多精选项目
     */
    public function moreProjects(){
        return '更多精选项目';
    }
    public function oneProjects($id){
        $info=Projects::getOneProjects($id);
        if(empty($info)){
          return redirect('/?navigation_id=0')->withErrors('项目不存在');
        }
        //投资明细
        $invest=ProjectsUser::where('projects_id',$info->id)->paginate(10);
        $links=(new BoosstrapPageProject($invest))->render();
        //可以使用的红包
        $grant_rule='gift_grant_rule_3';
        if($info->new_projects){
            $grant_rule='gift_grant_rule_8';
        }
        $gift=GiftActivity::where(['cate_id'=>$info->gift_cate,'status'=>1])->where('grant_rule',$grant_rule)->where('begin_time','<=',date('Y-m-d H:i:s'))->value('name');
        //项目属性
        $type_attr=ProjectAttr::where('project_id',$info->id)->orderBy('sort','desc')->get();
        //分润模板的角色比例
        $modes = ProfitRole::where('profit_id','=',$info->profits_cate)->get();
        $collection=collect($modes->toArray());
        $modes->total=$collection->sum('scale');

        $user=User::user();
        $sina_balance='';
        if(!empty($user)){
            //查询余额
            $sina_balance=$user->queryBalance();
        }
        return view("web.project.index",compact('info','type_attr','modes','invest','links','sina_balance','gift'));
    }
    /**
     * 收益预算
     * @param  Request $q [description]
     */
    public function getProfit(Request $q){
        $data=$q->all();
        $info=Projects::getOneProjects($data['id']);
        $money=floatval($data['money']);
        return json_encode($info->getProfit($money));
    }
    /**
     * 查看可用的投资红包
     * @return [type] [description]
     */
    public function getGift($money,$id){
        $result=Projects::getGift($money,$id);
        return json_encode($result);
    }
    public function icpIconOne(){
        return redirect('http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=50019002500122');

    }
    public function icpIconTwo(){
        return redirect('http://www.miitbeian.gov.cn/publish/query/indexFirst.action');
    }
    /**
     * 风险备付金
     */
    public function getfxbj(){
        //风险备付金
        $params['identity_id']=config('sinapay.partner_id');
        $params['identity_type']='MEMBER_ID';
        $params['account_type']='ENSURE';
        var_dump($params);
//        dd($params);
        $bei_fu_jin_reasult=QueryBalance::send($params);
        dd($bei_fu_jin_reasult);
    }

}